package de.sbi.AHLibjson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author sb
 * 
 */
public class FactionContainer {

	public Auction[] auctions;

	public Map<String, Map<Object, List<Auction>>> cache;

	public static final String C_TYPE_ITEM = "ITEM";

	@Override
	public String toString() {
		return "FactionContainer [auctions=" + Arrays.toString(auctions) + "]";
	}

	public FactionContainer(Auction[] auctions) {
		super();
		this.auctions = auctions;
	}

	public Auction[] getAuctions() {
		return auctions;
	}

	public void setAuctions(Auction[] auctions) {
		this.auctions = auctions;
	}

	public List<Auction> findItem(Long item) {
		List<Auction> resultListRef = null;

		if (item == null) {
			return new ArrayList<Auction>();
		}

		Map<Object, List<Auction>> auctionCacheMap = getTypeCacheMap(C_TYPE_ITEM);

		if (auctionCacheMap == null || auctionCacheMap.size() < 1) {
			// Build Cache
			for (int i = 0; i < this.auctions.length; i++) {
				Auction tmpAuction = this.auctions[i];

				Long itemId = tmpAuction.getItem();

				List<Auction> auctionList = getAuctionList(auctionCacheMap,
						itemId);

				auctionList.add(tmpAuction);

				if (itemId.equals(item)) {
					resultListRef = auctionList;
				}
			}
		} else {
			resultListRef = getAuctionList(auctionCacheMap, item);
		}

		return resultListRef;
	}

	public List<Auction> getAuctionList(Map<Object, List<Auction>> map,
			Object key) {
		List<Auction> auctionList = null;

		if (!map.containsKey(key)) {
			auctionList = new ArrayList<Auction>();
			map.put(key, auctionList);
		} else {
			auctionList = map.get(key);
		}

		return auctionList;
	}

	public Map<Object, List<Auction>> getTypeCacheMap(String type) {
		Map<Object, List<Auction>> auctionCacheMap = null;

		// LazyInit
		if (this.cache == null) {
			this.cache = new HashMap<String, Map<Object, List<Auction>>>();
		}

		if (!this.cache.containsKey(type)) {
			auctionCacheMap = new HashMap<Object, List<Auction>>();
			this.cache.put(type, auctionCacheMap);
		} else {
			auctionCacheMap = this.cache.get(type);
		}

		return auctionCacheMap;
	}
}
